package com.spark.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spark.common.constants.Constants;
import com.spark.common.core.Result;
import com.spark.common.query.QueryGenerator;
import com.spark.common.utils.TreeBuilderUtils;
import com.spark.common.utils.TreeIsLeafUtils;
import com.spark.modules.system.entity.SysPermission;
import com.spark.modules.system.service.ISysPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 系统权限菜单Controller
 *
 * @author LYCHEE
 * @date 2025/02/18 14:07
 */
@RestController
@RequestMapping(value = "/sys/permission")
public class SysPermissionController {

    @Resource
    private ISysPermissionService sysPermissionService;

    /**
     * 懒加载列表查询
     * : 如果pid为空则查询所有父级,反之查询子级数据
     *
     * @param sysPermission 系统权限菜单对象
     * @return 系统权限菜单列表
     */
    @PreAuthorize("@sp.hasPerm('sys:perm:query')")
    @GetMapping(value = "/queryLazyList")
    public Result<?> queryPageList(SysPermission sysPermission) {
        QueryWrapper<SysPermission> queryWrapper = QueryGenerator.initQueryWrapper(sysPermission);
        if (StringUtils.isEmpty(sysPermission.getPid())) {
            sysPermission.setPid("0");
        }
        List<SysPermission> list = sysPermissionService.list(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 列表查询
     * :结果支持两种结构。1.平级('flat') 2.层级('layer')
     * :需要再请求头中传入key为: model= 'flat' | 'layer'，默认 'layer'
     *
     * @param sysPermission 系统权限菜单对象
     * @return 系统权限菜单列表: 结果支持两种结构。1.平级('flat') 2.层级('layer')
     */
    @PreAuthorize("@sp.hasPerm('sys:perm:query')")
    @GetMapping(value = "/queryList")
    public Result<?> queryList(SysPermission sysPermission, HttpServletRequest request) {
        String model = request.getHeader(Constants.TREE_MODEL_KEY);
        model = StringUtils.isEmpty(model) ? "layer" : model;
        QueryWrapper<SysPermission> queryWrapper = QueryGenerator.initQueryWrapper(sysPermission);
        List<SysPermission> list = sysPermissionService.list(queryWrapper);
        if ("layer".equals(model)) {
            // 结构化为层级数据: 这里需要指定id,pid,children字段,此处为默认
            TreeBuilderUtils builder = new TreeBuilderUtils();
            // 结构化时设置叶子节点
            List<SysPermission> buildTree = builder.buildTree(list, true);
            // 可以按照某个属性进行排序
            // builder.sortTreeNodes(buildTree,"{排序实体字段}",true);
            return Result.ok(buildTree);
        }
        return Result.ok(list);
    }

    /**
     * 通过ID查询
     *
     * @param id 主键
     * @return 系统权限菜单对象
     */
    @PreAuthorize("@sp.hasPerm('sys:perm:queryById')")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam String id) {
        SysPermission sysPermission = sysPermissionService.getById(id);
        if (Objects.isNull(sysPermission)) {
            return Result.fail("数据获取失败");
        }
        return Result.ok(sysPermission);
    }

    /**
     * 新增
     *
     * @param sysPermission 系统权限菜单对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:perm:add')")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SysPermission sysPermission) {
        // 设置数据叶子节点：需要指定父级ID(pid)和叶子节点(isLeaf)字段名称，此处为默认
        TreeIsLeafUtils<SysPermission> isLeafUtils = new TreeIsLeafUtils<>(sysPermissionService);
        isLeafUtils.dealIsLeaf(sysPermission, "add", null);
        boolean save = sysPermissionService.save(sysPermission);
        return Result.flag(save);
    }

    /**
     * 编辑
     *
     * @param sysPermission 系统权限菜单对象
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:perm:edit')")
    @PostMapping(value = "/edit")
    public Result<?> edit(@RequestBody SysPermission sysPermission) {
        // 设置数据叶子节点：需要指定父级ID(pid)和叶子节点(isLeaf)字段名称，此处为默认
        TreeIsLeafUtils<SysPermission> isLeafUtils = new TreeIsLeafUtils<>(sysPermissionService);
        isLeafUtils.dealIsLeaf(sysPermission, "edit", null);
        boolean update = sysPermissionService.updateById(sysPermission);
        return Result.flag(update);
    }

    /**
     * 通过id删除
     *
     * @param id 主键
     * @return 成功或失败
     */
    @PreAuthorize("@sp.hasPerm('sys:perm:del')")
    @DeleteMapping(value = "/delete/{id}")
    public Result<?> delete(@PathVariable(name = "id") String id) {
        // 设置数据叶子节点：需要指定父级ID(pid)和叶子节点(isLeaf)字段名称，此处为默认
        TreeIsLeafUtils<SysPermission> isLeafUtils = new TreeIsLeafUtils<>(sysPermissionService);
        isLeafUtils.dealIsLeaf(null, "del", id);
        boolean update = sysPermissionService.removeById(id);
        return Result.flag(update);
    }

}
